﻿using System.Security;
using System.Windows.Forms;
using Microsoft.Win32;

namespace CloudShot.Utils
{
	public static class RegistryUtils
	{
		/// <summary>
		/// Add/Remove registry entries for windows startup.
		/// </summary>
		/// <param name="appName">Name of the application.</param>
		/// <param name="enable">if set to <c>true</c> [enable].</param>
		/// <returns>true if operation is successful; otherwise, false.</returns>
		public static bool SetStartup(string appName, bool enable)
		{
			const string runKey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";
			try
			{
				RegistryKey regKey = Registry.CurrentUser.OpenSubKey(runKey, true);

				if (regKey == null)
					return false;

				if (enable)
					regKey.SetValue(appName, Application.ExecutablePath); // Add or update startup reg key
				else
					regKey.DeleteValue(appName, false); // remove startup

				regKey.Close();
				return true;
			}
			catch (SecurityException err)
			{
				ErrorsHelper.TraceError(err);
				return false;
			}		
		}
	}
}
